package com.example.jacky.uilibrary.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.jacky.uilibrary.R;

import java.text.SimpleDateFormat;
import java.util.Date;


public class RefreshListView extends ListView implements OnScrollListener,
		OnItemClickListener {
	private static final int STATE_PULL = 0;
	private static final int STATE_RELEASE = 1;
	private static final int STATE_REFRESHING = 2;

	private int mCurrentState;
	private int startY = -1;
	private View mHeadView;
	private int mHeaderHeight;
	private View mFootView;
	private int mFooterHeight;

	public RefreshListView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public RefreshListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public RefreshListView(Context context) {
		super(context);
		init();
	}

	private void init() {
		initHeadView();
		initFootView();
		initAnim();
	}

	private void initAnim() {
		upAnim = new RotateAnimation(0, -180, Animation.RELATIVE_TO_SELF, 0.5f,
				Animation.RELATIVE_TO_SELF, 0.5f);
		upAnim.setDuration(200);
		upAnim.setFillAfter(true);

		downAnim = new RotateAnimation(-180, 0, Animation.RELATIVE_TO_SELF,
				0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		downAnim.setDuration(200);
		downAnim.setFillAfter(true);
	}

	/**
	 * 初始化脚布局
	 */
	private void initFootView() {
		mFootView = View.inflate(getContext(),
				R.layout.refresh_listview_footer, null);
		mFootView.measure(0, 0);
		mFooterHeight = mFootView.getMeasuredHeight();
		mFootView.setPadding(0, -mFooterHeight, 0, 0);
		this.addFooterView(mFootView);
		setOnScrollListener(this);
	}

	/**
	 * 初始化头布局
	 */
	private TextView tvTitle;
	private TextView tvTime;
	private ImageView ivArrow;
	private ProgressBar pbProgress;
	private RotateAnimation upAnim;
	private RotateAnimation downAnim;

	private void initHeadView() {
		mHeadView = View.inflate(getContext(), R.layout.refresh_listviwe_header, null);
		mHeadView.measure(0, 0);
		mHeaderHeight = mHeadView.getMeasuredHeight();
		mHeadView.setPadding(0, -mHeaderHeight, 0, 0);

		tvTitle = (TextView) mHeadView.findViewById(R.id.tv_title);
		tvTime = (TextView) mHeadView.findViewById(R.id.tv_time);
		ivArrow = (ImageView) mHeadView.findViewById(R.id.iv_arr);
		pbProgress = (ProgressBar) mHeadView.findViewById(R.id.pb_progress);

		this.addHeaderView(mHeadView);
		tvTime.setText("最后刷新时间:" + getCurrentTime());
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			startY = (int) ev.getY();
			break;
		case MotionEvent.ACTION_MOVE:
			if (mCurrentState == STATE_REFRESHING) {
				break;
			}
			if (startY == -1) {
				startY = (int) ev.getY();
			}
			int endY = (int) ev.getY();
			int dy = endY - startY;// dy>0下拉，dy<0上滑
			int padding = -mHeaderHeight + dy;
			mHeadView.setPadding(0, padding, 0, 0);

			if (getFirstVisiblePosition() == 0 && dy > 0) {// 只有下拉状态并且只有第一个item可见时，才允许下拉
				if (padding > 0 && mCurrentState != STATE_RELEASE) {
					mCurrentState = STATE_RELEASE;
					updateHeader();
				} else if (padding <= 0 && mCurrentState != STATE_PULL) {
					mCurrentState = STATE_PULL;
					updateHeader();
				}
			}

			break;
		case MotionEvent.ACTION_UP:
			startY = -1;// 重置
			if (mCurrentState == STATE_RELEASE) {
				mCurrentState = STATE_REFRESHING;
				mHeadView.setPadding(0, 0, 0, 0);// 显示
				updateHeader();
				if (listener != null) {
					listener.onRefreshing();
				}
			} else if (mCurrentState == STATE_PULL) {
				mHeadView.setPadding(0, -mHeaderHeight, 0, 0);
			}
			break;
		}
		return super.onTouchEvent(ev);
	}

	private void updateHeader() {
		switch (mCurrentState) {
		case STATE_PULL:
			tvTitle.setText("下拉刷新");
			ivArrow.setVisibility(View.VISIBLE);
			pbProgress.setVisibility(View.INVISIBLE);
			ivArrow.startAnimation(downAnim);
			break;
		case STATE_RELEASE:
			tvTitle.setText("松开刷新");
			ivArrow.setVisibility(View.VISIBLE);
			pbProgress.setVisibility(View.INVISIBLE);
			ivArrow.startAnimation(upAnim);
			break;
		case STATE_REFRESHING:
			tvTitle.setText("正在刷新...");
			ivArrow.clearAnimation();// 必须先清除动画,才能隐藏
			ivArrow.setVisibility(View.INVISIBLE);
			pbProgress.setVisibility(View.VISIBLE);

			break;
		}
	}

	public String getCurrentTime() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
		return format.format(new Date());
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

	}

	private boolean isLoadingMore;

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (scrollState == SCROLL_STATE_IDLE
				|| scrollState == SCROLL_STATE_FLING) {
			if (getLastVisiblePosition() == getCount() - 1 && !isLoadingMore) {
				mFootView.setPadding(0, 0, 0, 0);
				setSelection(getCount() - 1);
				isLoadingMore = true;
				if (listener != null) {
					listener.onLoadingMore();
				}
			}
		}
	}

	OnItemClickListener mItemClickListener;
	@Override
	public void setOnItemClickListener(
			OnItemClickListener listener) {
		super.setOnItemClickListener(this);
		this.mItemClickListener = listener;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (mItemClickListener != null) {
			mItemClickListener.onItemClick(parent, view, position
					- getHeaderViewsCount(), id);
		}
	}

	public OnRefreshListener listener;
	public interface OnRefreshListener {
		/**
		 * 下拉刷新
		 */
		void onRefreshing();

		/**
		 * 加载更多
		 */
		void onLoadingMore();
	}
	public void setOnRefreshListener(OnRefreshListener listener) {
		this.listener = listener;
	}

	public void onRefreshFinish(boolean sucess) {
		if (isLoadingMore) {
			isLoadingMore = false;
			mFootView.setPadding(0, -mFooterHeight, 0, 0);
		} else {
			mCurrentState = STATE_PULL;
			mHeadView.setPadding(0, -mHeaderHeight, 0, 0);
			tvTitle.setText("下拉刷新");
			ivArrow.setVisibility(View.VISIBLE);
			pbProgress.setVisibility(View.INVISIBLE);
			if (sucess) {
				tvTime.setText("最后刷新时间:" + getCurrentTime());
			}
		}
	}

}
